package com.example.calculator;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Stack;

@RequestMapping("/calculator")
@RestController
public class EvalRPN {

    @RequestMapping("/soval")
    public String soval(String str) {
        if (str == null || str.length() == 0){
            return "null";
        }
        MidChangeEnd midChangeEnd = new MidChangeEnd();
        ArrayList<String> arr = midChangeEnd.midChangeEng(str);
        EvalRPN evalRPN = new EvalRPN();
        String ret = evalRPN.evalRPN(arr);
        return ret;
    }

    public String evalRPN(ArrayList<String> tokens) {
        //用栈来存储数值
        Stack<String> stack = new Stack<>();
        //创建自定义的加法和乘法的类
        Solution solution = new Solution();

        for (int i = 0; i < tokens.size(); i++) {
            if (isOperator(tokens.get(i))) {
                //是符号，出栈进行计算；然后将结果入栈
                String num2 = stack.pop();
                String num1 = stack.pop();
                switch(tokens.get(i).charAt(0)) {
                    case '+':
                        stack.push(solution.Add(num1, num2));
                        break;
                    case '-':
                        double a = Double.valueOf(num1) - Double.valueOf(num2);
                        if(a < 0) {
                            return "0";
                        }
                        stack.push(Double.toString(a));
                        break;
                    case '*':
                        stack.push(solution.Mul(num1, num2));
                        break;
                    case '/':
                        stack.push(Long.toString((long)(Double.valueOf(num1) / Double.valueOf(num2))));
                        break;
                }
            }else {
                //如果是数值就入栈
                stack.push(tokens.get(i));
            }
        }
        return stack.pop();
    }

    //判断str是否为符号
    public boolean isOperator(String str) {
        if (str.length() != 1) {
            return false;
        }
        if (str.charAt(0) == '+' || str.charAt(0) == '-' || str.charAt(0) == '*' || str.charAt(0) == '/') {
            return true;
        }
        return false;
    }
}
